import {Rule} from 'xhyk-tools/xhykApi'
import {var_i18n_placeText,var_i18n_getText} from "../i18nUtil/i18nUtil.js";

const myRule = new Rule()

// 生成规则方法。
// 必填列表required：{field: 'password',message: ''} 或 'name'
// 函数验证fnList：{field: 'password',fn: function(rule, value, callBack)}
export const var_rule_makeRuleList = (required = [], fnList = []) => {
  let result = {}

  // region 添加必填选项
  required.forEach(row => {
    if (typeof row == 'string') {
      const requiredObj = {
        required: true,
        trigger: ['blur', 'change'],
        // 默认是国际化文本
        message: var_i18n_placeText(`fieldText.${row}`)
      }
      if (result[row]) {
        result[row].push(requiredObj)
      } else {
        result[row] = [requiredObj]
      }
    } else {
      const requiredObj = {
        required: true,
        trigger: ['blur', 'change'],
        // 默认是国际化文本
        message: row.message ? row.message : var_i18n_placeText(`fieldText.${row.field}`)
      }
      if (result[row.field]) {
        result[row.field].push(requiredObj)
      } else {
        result[row.field] = [requiredObj]
      }
    }
  })
  // endregion


  // region 函数验证
  fnList.forEach(row => {
    if (typeof row.fn == 'function') {
      const requiredObj = {
        trigger: ['blur', 'change'],
        validator: row.fn
      }
      if (result[row.field]) {
        result[row.field].push(requiredObj)
      } else {
        result[row.field] = [requiredObj]
      }
    }
  })

  // endregion

  return result;
}


// region 常用的验证方法

/*
* let result = var_rule_makeRuleList(['account', 'password'], [
    {field: 'password', fn: var_rule_fnList.isPassWord}
  ])
*  */

export const var_rule_fnList = {

  // region 是否为空或密码文本
  isPassWord: (rule, value, callBack) => {
    if (typeof value != 'string' || value.length <= 0) {
      callBack()
    }
    if (myRule.isPassWord(value)) {
      callBack()
    } else {
      let text = var_i18n_getText('ruleText.isPassWord')
      callBack(new Error(text))
    }
  },
  // endregion

  // region 是否为空或邮箱
  isEmail: (rule, value, callBack) => {
    if (typeof value != 'string' || value.length <= 0) {
      callBack()
    }
    if (myRule.isEmail(value)) {
      callBack()
    } else {
      let text = "邮箱格式不正确"
      callBack(new Error(text))
    }
  },
  // endregion

  // region 是否为空或手机号
  isPhone: (rule, value, callBack) => {
    if (typeof value != 'string' || value.length <= 0) {
      callBack()
    }
    if (myRule.isPhone(value)) {
      callBack()
    } else {
      callBack(new Error('手机号格式不正确'))
    }
  },
  // endregion

  // region 是否为空或编号
  isCode: (rule, value, callBack) => {
    if (typeof value != 'string' || value.length <= 0) {
      callBack()
    }
    if (myRule.isPassWord(value)) {
      callBack()
    } else {
      let text = var_i18n_getText('rules.isPassWord')
      callBack(new Error(text))
    }
  },
  // endregion

}
// endregion
